package com.seguriapp.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seguriapp.util.Util;

/**
 * Represents the controller for the resources entities
 * 
 * @author Tania Gonzales(taniadgv@gmail.com)
 */
@Controller
@RequestMapping("/resources")
public class ResourceController {

  private static final Logger LOGGER = Logger.getLogger(ResourceController.class);

  @RequestMapping("/image/{imageName}")
  public String getImageResource(final HttpServletRequest request, @PathVariable String imageName) {
    return getResourceRedirectUrl(request, imageName, Util.IMAGES_DIR);
  }

  @RequestMapping("/video/{videoName}")
  public String getVideoResource(final HttpServletRequest request, @PathVariable String videoName) {
    return getResourceRedirectUrl(request, videoName, Util.VIDEOS_DIR);
  }

  @RequestMapping("/audio/{audioName}")
  public String getAudioResource(final HttpServletRequest request, @PathVariable String audioName) {
    return getResourceRedirectUrl(request, audioName, Util.AUDIOS_DIR);
  }

  private String getResourceRedirectUrl(final HttpServletRequest request, final String resourceName, final String dirName) {
    final String fileName = new String(Base64.decodeBase64(resourceName.getBytes()));
    LOGGER.info("Required resource: " + fileName);
    return "redirect:" + "/uploaded" + dirName + fileName;
  }

}
